//
//  HiCodeController.m
//  HiCar
//
//  Created by 丁一 on 2019/1/8.
//  Copyright © 2019 丁一. All rights reserved.
//

#import "HiCodeController.h"
#import "YNTextField.h"
#import "GetCodeViewModel.h"
#import "RegionViewModel.h"
#import "JSMSSDK.h"
#import "HiJonesClass.h"
#import "UploadPSViewModel.h"

@interface HiCodeController ()<UITextFieldDelegate,YNTextFieldDelegate,GetCodeDelegate,RegionDelegate,UploadPSDelegate>{
    BOOL Delet_OK;
    NSString *Nowcode;
}

@property (nonatomic, strong) YNTextField *Codeone;
@property (nonatomic, strong) YNTextField *Codetwo;
@property (nonatomic, strong) YNTextField *Codethree;
@property (nonatomic, strong) YNTextField *Codefour;
@property (nonatomic, strong) YNTextField *Codefive;
@property (nonatomic, strong) YNTextField *Codesix;

@property (nonatomic, strong) UIButton    *forgitButton;
@property (nonatomic, strong) UIButton    *DoneButton;

@end

@implementation HiCodeController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title=@"短信验证";
    
    [self setView];
    [_Codeone becomeFirstResponder];
    self.view.backgroundColor = LineColor;
    Delet_OK = NO;
    [self getcode];
}

- (void)ynTextFieldDeleteBackward:(YNTextField *)textField{
    Delet_OK = YES;
    
    _Codeone.text=nil;
    _Codetwo.text=nil;
    _Codethree.text=nil;
    _Codefour.text=nil;
    _Codefive.text=nil;
    _Codesix.text=nil;
    
    [_Codeone becomeFirstResponder];
}

-(void)valueChanged:(YNTextField *)textField{
    
    if (textField==_Codeone) {
//        [_DoneButton setBackgroundImage:[JonesClass createImageWithColor:[UIColor grayColor]] forState:UIControlStateNormal];
        if (_Codeone.text.length==1) {
            [_Codetwo becomeFirstResponder];
        }
    }
    if (textField==_Codetwo) {
//        [_DoneButton setBackgroundImage:[JonesClass createImageWithColor:[UIColor grayColor]] forState:UIControlStateNormal];
        if (_Codetwo.text.length==1) {
            [_Codethree becomeFirstResponder];
        }
    }
    if (textField==_Codethree) {
//        [_DoneButton setBackgroundImage:[JonesClass createImageWithColor:[UIColor grayColor]] forState:UIControlStateNormal];
        if (_Codethree.text.length==1) {
            [_Codefour becomeFirstResponder];
        }
    }
    if (textField==_Codefour) {
//        if (_Codefour.text.length==1) {
//
////            NSString *linshi=[NSString stringWithFormat:@"%@%@%@%@",_Codeone.text,_Codetwo.text,_Codethree.text,_Codefour.text];
//
////            [_DoneButton setBackgroundImage:[JonesClass createImageWithColor:[UIColor orangeColor]] forState:UIControlStateNormal];
//
//        }else if (_Codefour.text.length>1){
//            _Codefour.text=[_Codefour.text substringFromIndex:1];
//        }
        if (_Codefour.text.length==1) {
            [_Codefive becomeFirstResponder];
        }
    }
    if (textField==_Codefive) {
        if (_Codefive.text.length==1) {
            [_Codesix becomeFirstResponder];
        }
    }
    if (textField==_Codesix) {
        if (_Codesix.text.length==1) {
            
        }else if (_Codesix.text.length>1){
            _Codesix.text=[_Codesix.text substringFromIndex:1];
        }
    }
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    NSLog(@"cdscffffff");
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
    
    if (textField==_Codeone) {
        if (_Codeone.text.length==1) {
            [_Codetwo becomeFirstResponder];
        }
    }
    if (textField==_Codetwo) {
        if (_Codetwo.text.length==1) {
            [_Codethree becomeFirstResponder];
        }
    }
    if (textField==_Codethree) {
        if (_Codethree.text.length==1) {
            [_Codefour becomeFirstResponder];
        }
    }
    if (textField==_Codefour) {
        if (_Codefour.text.length==1) {
            [_Codefive becomeFirstResponder];
        }
    }
    if (textField==_Codefive) {
        if (_Codefive.text.length==1) {
            [_Codesix becomeFirstResponder];
        }
    }
    if (textField==_Codesix) {
        if (_Codesix.text.length==1) {
            NSLog(@"dssdf");
        }
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    NSLog(@"cdscaaaaa");
    return YES;
}

-(void)setView{
    
    CGFloat widht=RECRWITCH/8;
    
    _Codeone=[self labelT];
    _Codeone.frame=CGRectMake(widht/2, NAV_Height + 35, widht, widht);
    [self.view addSubview:_Codeone];
    
    _Codetwo=[self labelT];
    _Codetwo.frame=CGRectMake(widht/2+widht+widht/5, NAV_Height + 35, widht, widht);
    [self.view addSubview:_Codetwo];
    
    _Codethree=[self labelT];
    _Codethree.frame=CGRectMake(widht/2+widht*2+widht/5*2, NAV_Height + 35, widht, widht);
    [self.view addSubview:_Codethree];
    
    _Codefour=[self labelT];
    _Codefour.frame=CGRectMake(widht/2+widht*3+widht/5*3, NAV_Height + 35, widht, widht);
    [self.view addSubview:_Codefour];
    
    _Codefive=[self labelT];
    _Codefive.frame=CGRectMake(widht/2+widht*4+widht/5*4, NAV_Height + 35, widht, widht);
    [self.view addSubview:_Codefive];
    
    _Codesix=[self labelT];
    _Codesix.frame=CGRectMake(widht/2+widht*5+widht, NAV_Height + 35, widht, widht);
    [self.view addSubview:_Codesix];
    
    _forgitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _forgitButton.frame=CGRectMake(RECRWITCH/2-50, NAV_Height + 55 + widht, 100, 30);
    [_forgitButton addTarget:self action:@selector(getcode)  forControlEvents:UIControlEventTouchUpInside];
    [_forgitButton setBackgroundColor:[UIColor clearColor]];
    [_forgitButton.titleLabel setFont:[UIFont systemFontOfSize:13]];
    _forgitButton.userInteractionEnabled = NO;
    [self.view addSubview:_forgitButton];
    
    _DoneButton           = [[UIButton alloc] initWithFrame:CGRectMake(25, NAV_Height + 100 + widht, RECRWITCH-50, 43)];
    _DoneButton.layer.cornerRadius  = 6;
    _DoneButton.layer.masksToBounds = YES;
    [_DoneButton setTitle:@"完  成" forState:UIControlStateNormal];
    [_DoneButton.titleLabel setFont:[UIFont boldSystemFontOfSize:17]];
    [_DoneButton addTarget:self action:@selector(go_done:) forControlEvents:UIControlEventTouchUpInside];
    [_DoneButton setBackgroundImage:[JonesClass createImageWithColor:Buttoncolor] forState:UIControlStateNormal];
    [_DoneButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:_DoneButton];
}

- (void)getcode{
    NSMutableDictionary *dic=[NSMutableDictionary new];
    [dic setValue:_phone forKey:@"phone"];
    if (_Type==0) {
        [dic setValue:@(2000) forKey:@"type"];
    }else{
        [dic setValue:@(1000) forKey:@"type"];
    }
    GetCodeViewModel *viewmodel = [[GetCodeViewModel alloc] init:dic];
    viewmodel.delegate=self;
}

- (void)Succes:(int)value code:(nonnull NSString *)code{
    if (value==1) {
        
        if ([DEFAULTS objectForKey:@"DUANXINCOUNT"]) {
            NSInteger lin_count = [[DEFAULTS objectForKey:@"DUANXINCOUNT"] integerValue] + 1;
            
            if (lin_count>16) {
                [SVProgressHUD showErrorWithStatus:@"本机操作受限"];
                return;
            }
            
            [DEFAULTS setValue:[NSString stringWithFormat:@"%li",(long)lin_count] forKey:@"DUANXINCOUNT"];
        }
 
        [JSMSSDK getVerificationCodeWithPhoneNumber:_phone andTemplateID:@"1" completionHandler:^(id resultObject, NSError *error) {
            if (!error) {
                NSLog(@"获取验证码成功！");
                [self updateGetCodeState];
                self->Nowcode = code;
            }else{
                NSLog(@"获取验证码失败！");
                __block NSString *error_str;
                __block NSString *error_code = [NSString stringWithFormat:@"%li",(long)error.code];
                NSDictionary *carlist=[HiJonesClass readLocalFileWithName:@"report"];
                [[carlist objectForKey:@"duanxincode"] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    NSDictionary *lindic = (NSDictionary *)obj;
                    if ([lindic objectForKey:error_code]) {
                        error_str = [lindic objectForKey:error_code];
                        *stop = YES;
                    }
                }];
                if (!error_str) {
                    error_str = @"获取验证码失败";
                }
                [SVProgressHUD showErrorWithStatus:error_str];

                [self->_forgitButton setTitle:@"重新获取验证码" forState:UIControlStateNormal];
                self->_forgitButton.userInteractionEnabled = YES;
                [self->_forgitButton setTitleColor:Buttoncolor forState:UIControlStateNormal];
            }
        }];
    }
}

-(void)updateGetCodeState{
    __block int timeout=60;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0)
        {
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self->_forgitButton setTitle:@"重新获取验证码" forState:UIControlStateNormal];
                self->_forgitButton.userInteractionEnabled = YES;
                [self->_forgitButton setTitleColor:Buttoncolor forState:UIControlStateNormal];
            });
        }else{
            int seconds = timeout % 60;
            if (timeout == 60){
                seconds = 60;
            }
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self->_forgitButton setTitle:[NSString stringWithFormat:@"重新获取%@秒",strTime] forState:UIControlStateNormal];
                self->_forgitButton.userInteractionEnabled = NO;
                [self->_forgitButton setTitleColor:[JonesClass stringTOColor:@"#333333"] forState:UIControlStateNormal];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

- (void)sendsms{
    
}

- (void)go_done:(UIButton *)sender{
    if (_Codeone.text.length==0||_Codetwo.text.length==0||_Codethree.text.length==0||_Codefour.text.length==0||_Codefive.text.length==0||_Codesix.text.length==0) {
        return;
    }
    NSString *linshi=[NSString stringWithFormat:@"%@%@%@%@%@%@",_Codeone.text,_Codetwo.text,_Codethree.text,_Codefour.text,_Codefive.text,_Codesix.text];
    
    
    NSString *name = [_phone stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    int x = arc4random() % 10;
    NSString *logo = [NSString stringWithFormat:@"https://xiangguo-app.oss-cn-beijing.aliyuncs.com/000News/%d.jpg",x];
    
    
    [JSMSSDK commitWithPhoneNumber:_phone verificationCode:linshi completionHandler:^(id resultObject, NSError *error) {
        if (!error) {
            NSLog(@"验证验证码成功！");
            if (self->_Type==1) {

                RegionViewModel *viewmodel = [[RegionViewModel alloc] init:@{@"phone":self->_phone,@"password":[JonesClass md5:self->_password],@"code":self->Nowcode,@"codetype":@(1000),@"name":name,@"logo":logo,@"briday":@"1990-08-08"}];
                viewmodel.delegate=self;
            }else if (self->_Type==0){
                
                UploadPSViewModel *viewmodel = [[UploadPSViewModel alloc] init:@{@"phone":self->_phone,@"password":[JonesClass md5:self->_password],@"code":self->Nowcode,@"codetype":@(2000)}];
                viewmodel.delegate=self;
            }
        }else{
            NSLog(@"验证验证码失败！");
            NSLog(@"%@", error);
            __block NSString *error_str;
            __block NSString *error_code = [NSString stringWithFormat:@"%li",(long)error.code];
            NSDictionary *carlist=[HiJonesClass readLocalFileWithName:@"report"];
            [[carlist objectForKey:@"duanxincode"] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSDictionary *lindic = (NSDictionary *)obj;
                if ([lindic objectForKey:error_code]) {
                    error_str = [lindic objectForKey:error_code];
                    *stop = YES;
                }
            }];
            if (!error_str) {
                error_str = @"未知错误";
            }
            [SVProgressHUD showErrorWithStatus:error_str];
        }
    }];
    
//    if (Nowcode&&[Nowcode isEqualToString:linshi]) {
//        if (_Type==1) {
//
//            RegionViewModel *viewmodel = [[RegionViewModel alloc] init:@{@"phone":_phone,@"password":[JonesClass md5:_password],@"code":Nowcode,@"codetype":@(1000)}];
//            viewmodel.delegate=self;
//        }else if (_Type==0){
//
//        }
//    }else{
//        [SVProgressHUD showErrorWithStatus:@"验证码错误！"];
//    }
}

- (void)RegionSucces:(int)value{
    if (value==1) {
        [SVProgressHUD showSuccessWithStatus:@"注册成功!"];
        [self gobackRoot];
    }
}

-(void)UploadPSSucces:(int)value{
    if (value==1) {
        [SVProgressHUD showSuccessWithStatus:@"修改成功!"];
        [self gobackRoot];
    }
}

-(YNTextField *)labelT{
    YNTextField *title=[[YNTextField alloc] init];
    title.textColor=[UIColor blackColor];
    title.font=[UIFont systemFontOfSize:37];
    title.backgroundColor=[UIColor whiteColor];
    title.keyboardType = UIKeyboardTypeNumberPad;
    title.returnKeyType=UIReturnKeyDone;
    title.textAlignment=NSTextAlignmentCenter;
    title.layer.cornerRadius=2.0;
    title.delegate=self;
    title.yn_delegate=self;
    [title addTarget:self  action:@selector(valueChanged:)  forControlEvents:UIControlEventAllEditingEvents];
    return title;
}

@end
